#!/bin/bash -e

# get the values of $SNAP_DATA and $SNAP using the current symlink instead of
# the default behavior which has the revision hard-coded, which breaks after
# a refresh
SNAP_DATA_CURRENT=${SNAP_DATA/%$SNAP_REVISION/current}
SNAP_CURRENT=${SNAP/%$SNAP_REVISION/current}

# install all the config files from $SNAP/config/res/ into $SNAP_DATA/config,
# but if files already exist, don't over-write
mkdir -p "$SNAP_DATA/config"

# create profile dirs if needed
cd "$SNAP/config/"
find . -maxdepth 2 -type d -exec mkdir -p "$SNAP_DATA/config/"{} \;

# copy configuration files if needed and do replacement of the $SNAP,
# $SNAP_DATA, $SNAP_COMMON environment variables in the config files
find ./res -name "configuration.toml" | \
    while read -r fname; do
	if [ ! -f "$SNAP_DATA/config/$fname" ]; then
	    cp "./$fname" "$SNAP_DATA/config/$fname"

            sed -i -e "s@\$SNAP_COMMON@$SNAP_COMMON@g" \
                -e "s@\$SNAP_DATA@$SNAP_DATA_CURRENT@g" \
                -e "s@\$SNAP@$SNAP_CURRENT@g" \
                "$SNAP_DATA/config/$fname"
        fi
    done

# disable app-service-configurable initially because it specific requires configuration
# with a device profile that will be specific to each installation
snapctl stop --disable "$SNAP_INSTANCE_NAME.app-service-configurable"

# set default profile
snapctl set profile=default
